<template>
  <div class="container">
    <div class="sider">
      <div class="sider-header">
        <p class="p3">设备中心</p>
      </div>
      <div class="contain">
        <ul>
          <li v-for="(item, index) in listData" :key="index" @click="getSectorList(item.deviceUserId, index)" :class="activeEquip == item.deviceUserId ? 'equip-box-active' : ''">
            <div class="equip-box">
              <div class="equip equip-font" :class="equipClass(item)">
                <span class="equip-name">设备号</span>：
                <span class="equip-value">{{ item.deviceUserId|formatDeviceUserId }}</span>
              </div>
              <div class="equip equip-item" :class="equipClass(item)">
                <span class="equip-name">用户</span>：
                <span>{{ item.userName }}</span>
              </div>
              <div class="equip equip-item" :class="equipClass(item)">
                <span class="equip-name">状态</span>：
                <span>{{ item.deviceWorkingStatus !== 99 ? item.armingStatus : item.workingStatus }}</span>
              </div>
              <div class="equip equip-item" :class="equipClass(item)" v-if="item.deviceWorkingStatus === 99 && item.heartbeatTime">
                <span class="equip-name">离线时间</span>：
                <span>{{ item.heartbeatTime }}</span>
              </div>
              <div class="bottom-btn-box" v-if="item.deviceWorkingStatus !== 99">
                <button :disabled="item.deviceArmingStatus !== 0 && item.workingStatus!==99" :class="!(item.deviceArmingStatus !== 0 && item.workingStatus!==99) ? 'active-btn' : 'unactive-btn'" @click.stop="handleBF(96, item.deviceUserId)">布防</button>
                <button style="margin-left: 5px" :disabled="item.deviceArmingStatus === 0 && item.workingStatus!==99" :class="item.deviceArmingStatus !== 0 && item.workingStatus!==99 ? 'active-btn' : 'unactive-btn'" @click.stop="handleBF(97, item.deviceUserId)">撤防</button>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="main">
      <topHeader @setDialogShow="setDialogShow" :deviceUserId="deviceUserId"></topHeader>
      <div class="equip-list">
        <div class="equip" v-for="(item, index) in sectorList" :key="index">
          <dv-border-box-6 :color="['#57daff', '#57daff']" :style="{width:'200px',height:'150px'}">
            <div class="equip-left">
              <div>
                <div><span style="font-size: 24px" :class="fontClass(item)" class="iconfont icon-dunshandian"></span></div>
                <div style="margin-top: 12px">{{ item.status|formatData(item.status) }}</div></div>
                <div style="font-size: 30px;margin-left: 10px">{{ item.sectorNum|formatSectorNum }}</div>
            </div>
            <div class="equip-right">
              <span @click="sectorArming(192,item)">布防</span>
              <span @click="sectorArming(193,item)">撤防</span>
              <span @click="sectorArming(194,item)">旁路</span>
              <span @click="sectorArming(195,item)">恢复</span>
            </div>
          </dv-border-box-6>
        </div>

      </div>
    </div>
    <component :is="componentName" :showDiaolog="showDiaolog" @setDialogShow="setDialogShow"></component>
    <audio ref="audio">
      <source src=""/>
    </audio>
  </div>
</template>

<script>
import '@/assets/css/equipment.scss'
import '@/assets/css/public.css'
import '@/assets/css/index.scss'
import topHeader from '@/components/topHeader.vue'
import '@/assets/font/iconfont.css'
import equipmentRegister from "./equipmentRegister";
import customerList from './customerList.vue'
import addCustomer from './addCustomer.vue'
import alarmList from "@/views/alarmList.vue";
export default {

  name: "equipment",
  data(){
    return {
      componentName: '',
      showDiaolog: false,
      listData: [],
      sectorList: [],
      deviceUserId: null,
      activeEquip: 0,
    }
  },
  components: {
    topHeader,
    equipmentRegister,
    customerList,
    addCustomer,
    alarmList
  },
  computed: {
  },
  created() {
    this.getDeviceList()
    this.initWebSocket()
  },
  methods: {
    getDeviceList(deviceUserId) {
      this.request.get('/uozo-alarm/device/getDeviceList').then(res => {
        this.listData = res.list
        let params = deviceUserId ? deviceUserId : this.listData[0].deviceUserId
        this.getSectorList(params)
        this.deviceUserId = params
        this.activeEquip = params
      }).catch(err => {
        console.error(err)
        this.listData = []
        this.deviceUserId = null
      })
    },
    equipClass(data) {
      if (data.deviceArmingStatus !== 0 && data.deviceWorkingStatus !== 99) {
        // 布防
        return 'font_red'
      }
      if (data.deviceArmingStatus === 0 && data.deviceWorkingStatus !== 99) {
        // 布防
        return 'font_green'
      }
      if (data.deviceWorkingStatus === 99) {
        // 布防
        return 'font_grey'
      }
    },
    getSectorList(deviceUserId, index=0) {
      this.deviceUserId = deviceUserId
      this.activeEquip = deviceUserId
      this.request.get('/uozo-alarm/device/getSectorList', {
        deviceUserId: deviceUserId,
      }).then(res => {
        this.sectorList = res
      }).catch(err => {
        this.sectorList = []
      })
    },
    setDialogShow({ name, show }) {
      this.componentName = name
      this.showDiaolog = show
    },
    sectorArming(handleCode, item) {
      this.request.post('/uozo-alarm/device/updateSectorArmingStatus', {
        handleCode,
        sectorNum: item.sectorNum,
        deviceUserId: item.deviceUserId
      }).then(() => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        setTimeout(() => {
          this.getSectorList(item.deviceUserId)
        }, 6000)
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        });
      })
    },
    initWebSocket(){ //初始化weosocket
      console.log('websocket初始化')
      // const wsuri = "ws://shtest.wmtechzone.club:8882/uozo-alarm/websocket/byb";
      const userId = localStorage.getItem('realName')
      // const wsuri = `ws://39.171.62.195:8900/uozo-alarm/websocket/${userId}`;
      // const wsuri = `ws://127.0.0.1:8900/uozo-alarm/websocket/${userId}`
      const wsuri = `ws://${location.host}/uozo-alarm/websocket/${userId}`
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen(){ //连接建立之后执行send方法发送数据
      let actions = {"test":"byb"};
      console.log('open')
      this.websocketsend(JSON.stringify(actions));
    },
    websocketonerror(){//连接建立失败重连
      setTimeout(function () {
        this.initWebSocket();
      }, 5000)
    },
    websocketonmessage(e){ //数据接收
      const redata = JSON.parse(e.data);
      if (redata.cidcode) {
        console.log('redata', redata)
        const userName = (redata.user && redata.user.name) || '无'
        const address = (redata.user && redata.user.address) || '无'
        let deviceUserId = this.formatDeviceUserId(redata.deviceUserId)
        let sectorNum = this.formatSectorNum(redata.sectorNum)
        if (redata.cidcode && (redata.cidcode.level != 4 && redata.cidcode.level != 5) ) {
          this.$notify({
            title: '警告',
            dangerouslyUseHTMLString: true,
            message: `<div>
                    <div>客户名称：${userName}</div>
                    <div>客户地址：${address}</div>
                    <div>接警时间：${redata.createTime}</div>
                    <div>报警时间：${redata.alarmTime}</div>
                    <div>报警类型：${redata.cidcode.alarmcontent}(CID:${redata.alarmCode})</div>
                    <div>报警主机：${deviceUserId}</div>
                    <div>报警防区：${sectorNum}</div>
          </div>`,
            type: 'warning',
            position: 'bottom-right',
            duration: 0,
            showClose: true,
            customClass: 'flicker'
          })
        }

        setTimeout(() => {
          this.getDeviceList(this.deviceUserId)
          this.getSectorList(this.deviceUserId)
        },6000)

        let music1 = new Audio();
        music1 = require("../assets/voice/alarm.mp3");
        this.$refs.audio.src = music1;
        this.$refs.audio.pause();
        this.$refs.audio.play();
      }
    },
    websocketsend(Data){//数据发送
      this.websock.send(Data);
    },
    websocketclose(e){  //关闭
      console.log('断开连接',e);
      setTimeout(function () {
        this.initWebSocket();
      }, 5000)
    },
    handleBF(handleCode, deviceUserId) {
      this.request.post('/uozo-alarm/device/updateDeviceArmingStatus', {
        deviceUserId,
        handleCode: handleCode
      }).then(() => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        });
      })
    },
    formatDeviceUserId(deviceUserId) {
      // 设备号不足8位的，在前边加“0”补足8位
      let length = deviceUserId.toString().length
      let plusString = 8 - length
      if (plusString > 0) {
        let str = ''
        for (let i = 0; i < plusString; i++) {
          str+='0'
        }
        return str + deviceUserId.toString()
      } else {
        return deviceUserId
      }
    },
    formatSectorNum(sectorNum) {
      // 防区号不足3位的，在前边加“0”补足3位
      let length = sectorNum.toString().length
      let plusString = 3 - length
      if (plusString > 0) {
        let str = ''
        for (let i = 0; i < plusString; i++) {
          str+='0'
        }
        return str + sectorNum.toString()
      } else {
        return sectorNum
      }
    },
    fontClass(item) {
      if (item.status == 1) {
        // 撤防
        return 'green'
      }
      if (item.status == 2) {
        // 布防
        return 'yellow'
      }
      if (item.status == 3) {
        // 旁路
        return 'blue'
      }
      if (item.status == 4) {
        // 旁路
        return 'red'
      }
    }
  },
  filters: {
    formatData(status){
      if (status == 1) {
        return '撤防'
      }
      if (status == 2) {
        return '布防'
      }
      if (status == 3) {
        return '旁路'
      }
      if (status == 4) {
        return '报警'
      }
    },
    formatDeviceUserId(deviceUserId) {
      // 设备号不足8位的，在前边加“0”补足8位
      let length = deviceUserId.toString().length
      let plusString = 8 - length
      if (plusString > 0) {
        let str = ''
        for (let i = 0; i < plusString; i++) {
          str+='0'
        }
        return str + deviceUserId.toString()
      } else {
        return deviceUserId
      }
    },
    formatSectorNum(sectorNum) {
      // 防区号不足3位的，在前边加“0”补足3位
      let length = sectorNum.toString().length
      let plusString = 3 - length
      if (plusString > 0) {
        let str = ''
        for (let i = 0; i < plusString; i++) {
          str+='0'
        }
        return str + sectorNum.toString()
      } else {
        return sectorNum
      }
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  background: url("../assets/images/bg.png") #0E2252;
  background-repeat: no-repeat;
  background-attachment: fixed;
  filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/background.jpg', sizingMethod='scale');
  -ms-filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/background.jpg', sizingMethod='scale');
  background-size: cover;
  -moz-background-size: cover;
  -webkit-background-size: cover;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  overflow: hidden;
}
.activeBtn {
  color: #FFFFFF;
}
.equip-list {
  width: 100%;
  max-height: calc(100% - 100px);
  overflow-y: auto;
  display: flex;
  justify-content: flex-start;
  flex-flow: row wrap;
  .border-box-content {
    display: flex;
    justify-content: space-around;
  }
  .equip {
    position: relative;
    display: flex;
    justify-content: space-between;
    margin-right: 30px;
    margin-bottom: 20px;

    .equip-left {
      top: 50%;
      transform: translatey(-50%);
      left: 15px;
      position: absolute;
      color: #bddde6;
      font-size: 18px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      width: 50%;
      word-break: keep-all;
      .equip-status {

      }
      .equip-name{

      }
    }
    .equip-right {
      height: 100%;
      position: absolute;
      right: 15px;
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
      span{
        display: block;
        color: #00EA37;
        cursor: pointer;
      }
    }

  }
}
.flicker {
  -webkit-animation: flicker 1s infinite;
  background: red;
  color: white;
}
@-webkit-keyframes flicker {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
.red {
  color: red;
}
.orange {
  color: orange;
}
.yellow {
  color: yellow;
}
.green {
  color: #00EA37;
}
.blue {
  color: #7171f9;
}
</style>
